package com.easy.framework.database.page;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.easy.framework.common.utils.Func;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 分页器
 *
 * @param <T>
 */
public class Pagination<T> extends SimplePage<T> implements Serializable {

    private static final long serialVersionUID = 1L;

    public Pagination() {

    }

    public Pagination(IPage page) {
        setTotal(page.getTotal());
        setRows(page.getRecords());
    }

    public Pagination(long total, List<T> rows) {
        super(total, rows);
        this.rows = rows;
    }

    public <C> Pagination<C> toPagination(Class<C> targetClazz) {
        Pagination<C> page = new Pagination<>();
        if (Func.isNotEmpty(getRows())) {
            List<C> outList = new ArrayList<>(getRows().size());
            for (Object source : getRows()) {
                if (source == null) {
                    continue;
                }
                C bean = BeanUtil.copyProperties(source, targetClazz);
                outList.add(bean);
            }
            page.setRows(outList);
            page.setTotal(getTotal());
        }
        return page;
    }


    public static <T> Pagination<T> toPagination(IPage page) {
        Pagination<T> pagination = new Pagination<>();
        pagination.setTotal(page.getTotal());
        pagination.setRows(page.getRecords());
        return pagination;
    }

    public static <C> Pagination<C> toPagination(IPage page, Class<C> targetClazz) {
        Pagination<C> pagination = new Pagination<>();
        if (null != page.getRecords()) {
            List<C> outList = new ArrayList<>(page.getRecords().size());
            for (Object source : page.getRecords()) {
                if (source == null) {
                    continue;
                }
                C bean = BeanUtil.copyProperties(source, targetClazz);
                outList.add(bean);
            }
            pagination.setRows(outList);
            pagination.setTotal(page.getTotal());
        }
        return pagination;
    }

    /**
     * 内存分页
     */
    public Pagination(Integer pageNum, Integer pageSize, List<T> rows) {
        setTotal(Long.valueOf(rows.size()));
        setRows(rows);
        if (rows.size() > 0) {
            Integer start = (pageNum - 1) * pageSize;
            Integer end = start + pageSize > rows.size() ? rows.size() : start + pageSize;
            List<T> pageList = rows.subList(start, end);
            setRows(pageList);
        }
    }


    public static <T> Pagination<T> emptyPage() {
        Pagination<T> pagination = new Pagination<>();
        pagination.setRows(Collections.emptyList());
        return pagination;
    }
}
